package org.darkforest.common.services.impl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.common.services.BusinessPropertiesService;
import org.darkforest.common.services.EmployeeLevelIndexService;
import org.darkforest.enums.EmployeeLevel;
import org.darkforest.model.Member;
import org.darkforest.ucenter.service.MemberLevelService;
import org.darkforest.ucenter.service.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * EmployeeLevelIndexServiceImpl
 * Created by Justin on 15/6/14.
 */
@Service
public class EmployeeLevelIndexServiceImpl implements EmployeeLevelIndexService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeLevelIndexService.class);

    @Autowired
    private BusinessPropertiesService propertiesService;

    @Autowired
    @Qualifier("memberServiceImpl")
    private MemberService memberService;

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public Member getNextIndexMemberInLevel(EmployeeLevel level) {
        String propertyKey = LevelIndexKey.getKey(level);
        String indexStr = propertiesService.getProperty(propertyKey);
        if (StringUtils.isBlank(indexStr)) {
            List<Member> employees = memberLevelService.getEmployeesByLevel(level);
            if (CollectionUtils.isEmpty(employees)) {
                LOGGER.error("Employee level {} is null", level);
                return null;
            }
            cursorNext(level);
        }
        return memberService.findMemberById(Integer.valueOf(indexStr));
    }

    @Override
    public void cursorNext(EmployeeLevel level) {
        String propertyKey = LevelIndexKey.getKey(level);
        String indexStr = propertiesService.getProperty(propertyKey);
        List<Member> employees = memberLevelService.getEmployeesByLevel(level);
        if (CollectionUtils.isEmpty(employees)) {
            LOGGER.error("Employee level {} is null", level);
            return;
        }
        if (StringUtils.isBlank(indexStr)) {
            Member firstEmployee = employees.get(0);
            propertiesService.setProperty(propertyKey, firstEmployee.getMemberId().toString());
            return ;
        }

        Integer nextMemberId = LevelIndexKey.getNext(employees, indexStr);
        propertiesService.setProperty(propertyKey, "" + nextMemberId);
    }
}
